use mysql::*;
use mysql::prelude::*;
use std::thread;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::fs::OpenOptions;
use std::io::Write;
use std::time::Instant;

fn main() {
    // 开始计时
    let start_time = Instant::now();

    // 创建数据库连接池
    let pool = Pool::new("mysql://xytest:a5M2Y56Hg8wWbq@172.16.2.86:3306/hreader").unwrap();
    let pool = Arc::new(Mutex::new(pool));

    // 创建全局计数器
    let counter = Arc::new(AtomicUsize::new(0));

    // 先清空文件内容
    OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open("user_info.txt")
        .unwrap();
    
    // 重新以追加模式打开文件
    let file = OpenOptions::new()
        .create(true)
        .append(true)
        .open("user_info.txt")
        .unwrap();
    let file = Arc::new(Mutex::new(file));

    // 获取表的总记录数
    let mut conn = pool.lock().unwrap().get_conn().unwrap();
    let total_count: u64 = conn.query_first("SELECT COUNT(*) FROM user_info")
        .unwrap().unwrap();
    
    println!("总记录数: {}", total_count);
    
    let threads = 8;
    let chunk_size = total_count / threads as u64;

    println!("每个线程处理 {} 条记录", chunk_size);

    // 创建线程来并发查询
    let mut handles = vec![];

    for i in 0..threads {
        let pool = Arc::clone(&pool);
        let counter = Arc::clone(&counter);
        let file = Arc::clone(&file);
        let offset = i as u64 * chunk_size;

        // 最后一个线程处理剩余的记录
        let limit = if i == threads - 1 {
            total_count - offset // 剩余的所有记录
        } else {
            chunk_size
        };
        //多线程查询
        let handle = thread::spawn(move || {
            let mut conn = pool.lock().unwrap().get_conn().unwrap();
            let query = format!(
                "SELECT no,open_id FROM user_info ORDER BY no ASC LIMIT {} OFFSET {}",
                limit, offset
            );

            println!("线程 {} 开始执行查询: {}", i, query);

            // 执行查询，将 open_id 作为字符串类型
            let result: Vec<Row> = conn.query(query).unwrap();
            for row in result {
                let open_id: String = row.get("open_id").unwrap_or_default();
                let no: String = row.get("no").unwrap_or_default();
                let current_count = counter.fetch_add(1, Ordering::SeqCst);
                
                // 写入文件
                let mut file = file.lock().unwrap();
                writeln!(file, "{}: 线程 {} - no: {}, open_id: {}", 
                    current_count + 1, i, no, open_id).unwrap();
            }
            
            println!("线程 {} 执行完成", i);
        });

        handles.push(handle);
    }

    // 等待所有线程执行完毕
    for handle in handles {
        handle.join().unwrap();
    }
    
    // 计算运行时间
    let duration = start_time.elapsed();
    println!("所有查询已完成，结果已写入 user_info.txt");
    println!("总运行时间: {:.2}秒", duration.as_secs_f64());
}